package com.tanhua.sso.controller;

import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.sso.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
/**
 * 注册时发送验证码服务
 */
@Component
@RestController
@RequestMapping("user")
@Slf4j
public class SmsController {

    @Autowired
    private SmsService smsService;

    /**
     * 发送验证码
     * @return //ResponseEntity<Object>
     */
    //这里前端应该是只传一个参数--json格式的phone(String)
    @PostMapping("login")
    public ResponseEntity<Object> sendCheckCode(@RequestBody Map<String, Object> param) {//变成JSON格式是序列化,解析JSON是反序列化
        log.info("给此手机号发送验证码: {}", param);

        ErrorResult.ErrorResultBuilder resultBuilder = ErrorResult.builder().errCode("000000").errMessage("发送短信验证码失败");
            String phone = String.valueOf(param.get("phone"));//拿到手机号
            Map<String, Object> sendCheckCode = this.smsService.sendCheckCode(phone);
            int code = ((Integer) sendCheckCode.get("code")).intValue();
            if (code == 3) {
                return ResponseEntity.ok(null);
                //走到这,发送验证码成功,发了一个新验证码,return发送成功
            }else if(code == 1){
                String msg = sendCheckCode.get("msg").toString();
                resultBuilder.errCode("000001").errMessage(msg);
                //走到这,发送验证码不成功,但redis里还存了一个没过期的,return的是发送失败
            }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultBuilder.build());//HttpStatus.INTERNAL_SERVER_ERROR:错误500
    }
}
